"""
能力注册表

管理数据源适配器的能力信息，支持快速查询和匹配。

功能：
1. 注册适配器能力
2. 查询支持特定能力的适配器
3. 能力匹配和评分
4. 缓存和性能优化

作者: RedFire Team
创建日期: 2025-10-06
版本: v1.0
"""

from typing import Dict, List, Set, Optional, Any
from dataclasses import dataclass, field
import logging
from collections import defaultdict

from app.adapters.base import BaseMarketDataAdapter
from app.adapters.core.capabilities import (
    DataCapability,
    MarketCapability,
    PerformanceLevel,
    DataFreshness
)


@dataclass
class AdapterCapabilityInfo:
    """
    适配器能力信息
    
    存储单个适配器的完整能力信息。
    
    Attributes:
        adapter_name: 适配器名称
        data_capabilities: 数据能力集合
        market_capabilities: 市场能力集合
        performance_level: 性能级别
        data_freshness: 数据新鲜度
        cost_level: 成本级别
        reliability_score: 可靠性分数
        metadata: 额外元数据
    """
    adapter_name: str
    data_capabilities: Set[DataCapability] = field(default_factory=set)
    market_capabilities: Set[MarketCapability] = field(default_factory=set)
    performance_level: PerformanceLevel = PerformanceLevel.MEDIUM
    data_freshness: DataFreshness = DataFreshness.DELAYED
    cost_level: int = 3
    reliability_score: float = 0.8
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def has_data_capability(self, capability: DataCapability) -> bool:
        """检查是否有指定的数据能力"""
        return capability in self.data_capabilities
    
    def has_market_capability(self, capability: MarketCapability) -> bool:
        """检查是否有指定的市场能力"""
        return capability in self.market_capabilities
    
    def get_capability_count(self) -> int:
        """获取总能力数量"""
        return len(self.data_capabilities) + len(self.market_capabilities)
    
    def calculate_match_score(
        self,
        required_data_caps: Set[DataCapability],
        required_market_caps: Set[MarketCapability]
    ) -> float:
        """
        计算匹配分数
        
        Args:
            required_data_caps: 需要的数据能力
            required_market_caps: 需要的市场能力
        
        Returns:
            float: 匹配分数 (0-1)
        """
        if not required_data_caps and not required_market_caps:
            return 1.0
        
        total_required = len(required_data_caps) + len(required_market_caps)
        if total_required == 0:
            return 1.0
        
        matched_data = len(required_data_caps & self.data_capabilities)
        matched_market = len(required_market_caps & self.market_capabilities)
        matched_total = matched_data + matched_market
        
        return matched_total / total_required


class CapabilityRegistry:
    """
    能力注册表
    
    管理所有适配器的能力信息，提供快速查询和匹配功能。
    
    主要功能：
    1. 注册/注销适配器
    2. 查询支持特定能力的适配器
    3. 能力匹配和评分
    4. 适配器健康状态管理
    """
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        """
        初始化能力注册表
        
        Args:
            logger: 日志记录器
        """
        self.logger = logger or logging.getLogger(__name__)
        
        # 适配器能力信息存储
        self._adapters: Dict[str, AdapterCapabilityInfo] = {}
        
        # 反向索引：数据能力 -> 适配器列表
        self._data_capability_index: Dict[DataCapability, Set[str]] = defaultdict(set)
        
        # 反向索引：市场能力 -> 适配器列表
        self._market_capability_index: Dict[MarketCapability, Set[str]] = defaultdict(set)
        
        # 适配器健康状态
        self._adapter_health: Dict[str, bool] = {}
        
        # 适配器实例缓存
        self._adapter_instances: Dict[str, BaseMarketDataAdapter] = {}
    
    def register_adapter(
        self,
        adapter: BaseMarketDataAdapter,
        override: bool = False
    ) -> bool:
        """
        注册适配器
        
        Args:
            adapter: 适配器实例
            override: 是否覆盖已存在的注册
        
        Returns:
            bool: 是否注册成功
        """
        adapter_name = adapter.provider_name
        
        # 检查是否已存在
        if adapter_name in self._adapters and not override:
            self.logger.warning(f"适配器已存在: {adapter_name}")
            return False
        
        try:
            # 获取能力声明
            caps = adapter.get_capabilities()
            
            # 创建能力信息
            info = AdapterCapabilityInfo(
                adapter_name=adapter_name,
                data_capabilities=caps.data_capabilities,
                market_capabilities=caps.market_capabilities,
                performance_level=caps.performance_level,
                data_freshness=caps.data_freshness,
                cost_level=caps.cost_level,
                reliability_score=caps.reliability_score,
                metadata=caps.metadata
            )
            
            # 存储信息
            self._adapters[adapter_name] = info
            
            # 更新反向索引
            for cap in caps.data_capabilities:
                self._data_capability_index[cap].add(adapter_name)
            
            for cap in caps.market_capabilities:
                self._market_capability_index[cap].add(adapter_name)
            
            # 初始化健康状态
            self._adapter_health[adapter_name] = True
            
            # 缓存实例
            self._adapter_instances[adapter_name] = adapter
            
            self.logger.info(
                f"注册适配器成功: {adapter_name}, "
                f"数据能力={len(info.data_capabilities)}, "
                f"市场能力={len(info.market_capabilities)}"
            )
            return True
            
        except Exception as e:
            self.logger.error(f"注册适配器失败 {adapter_name}: {e}")
            return False
    
    def unregister_adapter(self, adapter_name: str) -> bool:
        """
        注销适配器
        
        Args:
            adapter_name: 适配器名称
        
        Returns:
            bool: 是否注销成功
        """
        if adapter_name not in self._adapters:
            self.logger.warning(f"适配器不存在: {adapter_name}")
            return False
        
        try:
            info = self._adapters[adapter_name]
            
            # 清理反向索引
            for cap in info.data_capabilities:
                self._data_capability_index[cap].discard(adapter_name)
            
            for cap in info.market_capabilities:
                self._market_capability_index[cap].discard(adapter_name)
            
            # 删除信息
            del self._adapters[adapter_name]
            self._adapter_health.pop(adapter_name, None)
            self._adapter_instances.pop(adapter_name, None)
            
            self.logger.info(f"注销适配器成功: {adapter_name}")
            return True
            
        except Exception as e:
            self.logger.error(f"注销适配器失败 {adapter_name}: {e}")
            return False
    
    def get_adapters_by_data_capability(
        self,
        capability: DataCapability,
        only_healthy: bool = True
    ) -> List[str]:
        """
        获取支持指定数据能力的适配器
        
        Args:
            capability: 数据能力
            only_healthy: 是否只返回健康的适配器
        
        Returns:
            List[str]: 适配器名称列表
        """
        adapters = list(self._data_capability_index.get(capability, set()))
        
        if only_healthy:
            adapters = [a for a in adapters if self._adapter_health.get(a, False)]
        
        return adapters
    
    def get_adapters_by_market_capability(
        self,
        capability: MarketCapability,
        only_healthy: bool = True
    ) -> List[str]:
        """
        获取支持指定市场能力的适配器
        
        Args:
            capability: 市场能力
            only_healthy: 是否只返回健康的适配器
        
        Returns:
            List[str]: 适配器名称列表
        """
        adapters = list(self._market_capability_index.get(capability, set()))
        
        if only_healthy:
            adapters = [a for a in adapters if self._adapter_health.get(a, False)]
        
        return adapters
    
    def find_matching_adapters(
        self,
        data_capabilities: Optional[Set[DataCapability]] = None,
        market_capabilities: Optional[Set[MarketCapability]] = None,
        min_match_score: float = 0.5,
        only_healthy: bool = True
    ) -> List[tuple[str, float]]:
        """
        查找匹配的适配器
        
        Args:
            data_capabilities: 需要的数据能力
            market_capabilities: 需要的市场能力
            min_match_score: 最小匹配分数
            only_healthy: 是否只返回健康的适配器
        
        Returns:
            List[tuple[str, float]]: (适配器名称, 匹配分数) 列表，按分数降序排列
        """
        data_caps = data_capabilities or set()
        market_caps = market_capabilities or set()
        
        results = []
        
        for adapter_name, info in self._adapters.items():
            # 健康检查
            if only_healthy and not self._adapter_health.get(adapter_name, False):
                continue
            
            # 计算匹配分数
            score = info.calculate_match_score(data_caps, market_caps)
            
            if score >= min_match_score:
                results.append((adapter_name, score))
        
        # 按分数降序排列
        results.sort(key=lambda x: x[1], reverse=True)
        
        return results
    
    def get_adapter_info(self, adapter_name: str) -> Optional[AdapterCapabilityInfo]:
        """
        获取适配器能力信息
        
        Args:
            adapter_name: 适配器名称
        
        Returns:
            Optional[AdapterCapabilityInfo]: 能力信息
        """
        return self._adapters.get(adapter_name)
    
    def get_adapter_instance(self, adapter_name: str) -> Optional[BaseMarketDataAdapter]:
        """
        获取适配器实例
        
        Args:
            adapter_name: 适配器名称
        
        Returns:
            Optional[BaseMarketDataAdapter]: 适配器实例
        """
        return self._adapter_instances.get(adapter_name)
    
    def set_adapter_health(self, adapter_name: str, is_healthy: bool):
        """
        设置适配器健康状态
        
        Args:
            adapter_name: 适配器名称
            is_healthy: 是否健康
        """
        if adapter_name in self._adapters:
            self._adapter_health[adapter_name] = is_healthy
            status = "健康" if is_healthy else "不健康"
            self.logger.info(f"适配器 {adapter_name} 状态更新: {status}")
    
    def get_all_adapter_names(self, only_healthy: bool = False) -> List[str]:
        """
        获取所有适配器名称
        
        Args:
            only_healthy: 是否只返回健康的适配器
        
        Returns:
            List[str]: 适配器名称列表
        """
        if only_healthy:
            return [
                name for name in self._adapters.keys()
                if self._adapter_health.get(name, False)
            ]
        return list(self._adapters.keys())
    
    def get_adapter_count(self, only_healthy: bool = False) -> int:
        """
        获取适配器数量
        
        Args:
            only_healthy: 是否只统计健康的适配器
        
        Returns:
            int: 适配器数量
        """
        if only_healthy:
            return sum(1 for h in self._adapter_health.values() if h)
        return len(self._adapters)
    
    def get_registry_stats(self) -> Dict[str, Any]:
        """
        获取注册表统计信息
        
        Returns:
            Dict[str, Any]: 统计信息
        """
        return {
            "total_adapters": len(self._adapters),
            "healthy_adapters": sum(1 for h in self._adapter_health.values() if h),
            "data_capabilities_count": len(self._data_capability_index),
            "market_capabilities_count": len(self._market_capability_index),
            "adapters": [
                {
                    "name": name,
                    "healthy": self._adapter_health.get(name, False),
                    "data_caps": len(info.data_capabilities),
                    "market_caps": len(info.market_capabilities),
                    "performance": info.performance_level.name,
                    "freshness": info.data_freshness.name
                }
                for name, info in self._adapters.items()
            ]
        }
    
    def clear(self):
        """清空注册表"""
        self._adapters.clear()
        self._data_capability_index.clear()
        self._market_capability_index.clear()
        self._adapter_health.clear()
        self._adapter_instances.clear()
        self.logger.info("注册表已清空")

